import React, { Component } from 'react';
import {
    View,
    Text,
    TextInput,
    Button,
    TouchableOpacity,
    StyleSheet,
    DeviceEventEmitter
} from 'react-native'
import { NavigationActions } from 'react-navigation';
import KeyEvent from 'react-native-keyevent'
import Icon from 'react-native-vector-icons/FontAwesome'
import Toast from 'react-native-root-toast';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { unshiftInventroy } from '../../actions/CheckAction';

import * as fetch from '../../utils/fetch'
import Style from '../../utils/style/style'
import WXStyle from '../../utils/style/wxstyle';
import QrCode from '../../views/qrCode';
import PrimaryButton from '../../views/primaryButton';
import MsgModal from '../../components/modal/errorModal';
import RfidModule from '../../components/Rfid';
import o from '../../components/o';
import moment from 'moment';
class ChecksAdd extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: null,
            disable: false,
            codesStr: '',
            codesArr: [],
            // codesArr: ['00011FFF000001AAAA000991', '00011FFF000001AAAA000992', '00011FFF000001AAAA000993', '00011FFF000001AAAA000994', '00011FFF000001AAAA000995', '00011FFF000001AAAA001005', '00011FFF000001AAAA001002', '00011FFF000001AAAA001007', '00011FFF000001AAAA001012'],
            // codesStr: '00011FFF000001AAAA000991,00011FFF000001AAAA000992,00011FFF000001AAAA000993,00011FFF000001AAAA000994,00011FFF000001AAAA001005,00011FFF000001AAAA001002,00011FFF000001AAAA001007,00011FFF000001AAAA001012',
            modal: {
                title: '',
                msg: '',
                visible: false
            },
            BarCodeList: [],
            inventory: {
            },
        }
    }
    static navigationOptions = {
        title: '盘库',
    };

    componentWillMount() {
        //通过使用DeviceEventEmitter模块来监听原生模块发送过来的事件
        DeviceEventEmitter.addListener('onInventoryTag', (Event) => {
            //盘存标签触发回调
            let result = Event.RfidResult;
            let codesArr = this.state.codesArr;
            for (let i = 0; i < codesArr.length; i++) {
                if (codesArr[i] == result) {
                    return;
                }
            }
            codesArr.push(result);
            this.setState({
                codesArr: codesArr,
            })
        });
        DeviceEventEmitter.addListener('onInventoryTagEnd', (Event) => {
            if (Event.TagCount && Event.TagCount > 20) {
                this._showModal("失败", "批量扫描请控制在20个以内");
                this.setState({
                    codesArr:[],
                    codesStr:'',
                })
            } else {
                //盘存结束回调    
                if (this.state.codesArr.length > 0) {
                    this.setState({
                        codesStr: this.state.codesArr.join(',')
                    })
                }
            }


        });
        DeviceEventEmitter.addListener('onExeCMDStatus', (Event) => {
            this._showModal("失败", Event.ErrorMsg)
        })
        DeviceEventEmitter.addListener('getAllDevices', (Event) => {
            alert(Event.DevicesResult + "&&" + Event.PathResult);
        });
    }

    componentDidMount() {
        KeyEvent.onKeyDownListener((evt) => {
            //监听手持机的扫码头按下等操作？
        })
        // RfidModule.getAllDevices();
        RfidModule.open();
        RfidModule.openCom();
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (nextState.codesStr == this.state.codesStr && nextState.codesArr != this.state.codesArr) {
            //扫描标签即时回传过程中不调用render
            return false
        } else {
            return true
        }
    }
    _pressCode() {
        RfidModule.readRfid();
    }
    _submit() {
        if (this.state.codesArr.length == 0) {
            // this._back()
            return;
        } else {
            const { token } = this.props;
            o(`erp_goodss?token=${token}`).get().then((oHandler) => {
                const res = oHandler.data
                if (res && res.length > 0) {
                    this.setState({
                        BarCodeList: res
                    })
                }
                this._postData();
            }).fail((e) => {

            })
        }
    }

    _postData() {

        const BarCodeList = this.state.BarCodeList;
        const codesArr = this.state.codesArr;
        let LostList = [].concat(BarCodeList),//初始状态下所有的已存在的都假设为缺失
            RedundancyList = [],
            UnknownList = [].concat(codesArr),//初始状态下所有的已扫描的都假设为未知
            NormalList = [];

        for (let i = 0; i < BarCodeList.length; i++) {
            for (let j = 0; j < codesArr.length; j++) {
                if (BarCodeList[i].BarCode == codesArr[j]) {
                    if (BarCodeList[i].State == 1) {
                        NormalList.push(BarCodeList[i]);//正常状态
                    } else {
                        RedundancyList.push(BarCodeList[i]);//已出库的冗余序列号
                    }
                    let diff = BarCodeList.length - LostList.length;
                    let diff2 = codesArr.length - UnknownList.length;
                    let index = i == 0 ? 0 : Math.abs(i - diff)
                    let index2 = j == 0 ? 0 : Math.abs(j - diff2)
                    LostList.splice(index, 1);//删除并未缺失的
                    UnknownList.splice(index2, 1);//删除不是未知的
                    break;
                }
            }
        }
        let params = {
            LostList: LostList,
            RedundancyList: RedundancyList,
            UnknownList: UnknownList,
            NormalList: NormalList
        }
        this._postInvery(params);
    }

    //盘点
    _postInvery(params) {
        const { LostList, RedundancyList, UnknownList, NormalList } = params;
        const Lost = LostList.length,
            Redundancy = RedundancyList.length,
            Unknown = UnknownList.length,
            Normal = NormalList.length;
        const { TenantId, UserId } = this.props.userInfo
        let params2 = {
            InventoryId: UserId,
            inv_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            Lost: Lost,
            Redundancy: Redundancy,
            inv_unknown: Unknown,
            Normal: Normal,
            TenantId: TenantId
        }
        const { token } = this.props
        o(`erp_inventory?token=${token}`).post(params2).save().then(oHandler => {
            const res = oHandler.data;
            this.setState({
                inventory: res
            })
            console.log(this.state.inventory)
            this._postInvSerail(res);
            this._postInvResult(res, params);
        }).fail((e) => {
            Toast.show("新建盘点失败", {
                duration: Toast.durations.LONG,
                position: Toast.positions.CENTER,
            })
        })
    }

    //盘点结果
    _postInvResult(res, params) {
        const InventoryId = res.inv_id;
        const { LostList, RedundancyList, UnknownList, NormalList } = params;
        let index = LostList.length + RedundancyList.length + UnknownList.length + NormalList.length;
        let isLast = false;
        for (let i = 0; i < LostList.length; i++) {
            index--
            if (index == 0) {
                isLast = true
            }
            this._postDataToResult(InventoryId, LostList[i].GoodId, 1, LostList[i].BarCode, isLast)
        };
        for (let j = 0; j < RedundancyList.length; j++) {
            index--
            if (index == 0) {
                isLast = true
            }
            this._postDataToResult(InventoryId, RedundancyList[j].GoodId, 2, RedundancyList[j].BarCode, isLast)
        };
        for (let k = 0; k < UnknownList.length; k++) {
            index--
            if (index == 0) {
                isLast = true
            }
            this._postDataToResult(InventoryId, 0, 3, UnknownList[k], isLast)
        };
        for (let l = 0; l < NormalList.length; l++) {
            index--
            if (index == 0) {
                isLast = true
            }
            this._postDataToResult(InventoryId, NormalList[l].GoodId, 4, NormalList[l].BarCode, isLast)
        };

    }

    _postDataToResult(InventoryId, GoodId, Type, BarCode, isLast) {
        const { TenantId } = this.props.userInfo
        let params = {
            InventoryId: InventoryId,
            GoodId: GoodId,
            store_type: Type,
            BarCode: BarCode.toString(),
            TenantId: TenantId
        };
        const { token } = this.props;
        o(`erp_storehouse?token=${token}`).post(params).save().then(res => {
            if (isLast) {
                this._back();
            }
        }).fail((e) => {
            Toast.show("盘点结果异常", {
                duration: Toast.durations.LONG,
                position: Toast.positions.CENTER,
            })
        })
    }
    //盘点序列号表
    _postInvSerail(res) {
        const InventoryId = res.inv_id;
        const codesArr = this.state.codesArr;
        const { TenantId } = this.props.userInfo
        for (let i = 0; i < codesArr.length; i++) {
            let params = {
                InventoryId: InventoryId,
                BarCode: codesArr[i].toString(),
                TenantId: TenantId,
            }
            const { token } = this.props
            o(`erp_inv_seq?token=${token}`).post(params).save().then(res => { console.log(codesArr[i]) }).fail((e) => {
                Toast.show("盘点序列号添加异常", {
                    duration: Toast.durations.LONG,
                    position: Toast.positions.CENTER,
                })
            })
        }
    }

    _back() {
        const inventory = this.state.inventory;
        const params = { item: JSON.stringify(inventory) }
        //这里如何修改列表
        const navigateAction = NavigationActions.navigate({
            routeName: 'CheckDetail',
            params: params,
            action: NavigationActions.back({ routeName: 'Index' }),
        });
        this.props.unshiftInventroy(inventory);
        this.props.navigation.replace("CheckDetail", params);
    }

    _renderModal() {
        return (
            <MsgModal
                title={this.state.modal.title}
                msg={this.state.modal.msg}
                visible={this.state.modal.visible}
                pressBtn={() => this._hideModal()}
            />
        )
    }
    _showModal(title, msg) {
        this.setState({
            modal: {
                title: title,
                msg: msg,
                visible: true
            }
        })
    }
    _hideModal() {
        this.setState({
            disable: false,
            modal: {
                title: '',
                msg: '',
                visible: false
            }
        })
    }
    render() {
        return (
            <View style={styles.container}>
                <View style={styles.gap} />
                <QrCode pressCode={() => this._pressCode()} />
                <View style={styles.textWrap}>
                    <TextInput multiline={true} placeholder="扫描添加标签" editable={false} underlineColorAndroid="transparent" style={styles.textInput} value={this.state.codesStr} ></TextInput>
                </View>
                <PrimaryButton title="立即盘库" submit={() => this._submit()} disable={this.state.disable} />
                {this._renderModal()}
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        width: Style.width,
        height: Style.ViewHeightD,
        alignItems: 'center',
        backgroundColor: '#fff',
    },
    gapTop: {
        borderTopWidth: 1,
    },
    gap: {
        width: Style.width,
        height: 20,
        borderColor: '#e5e5e5',
        borderStyle: 'solid',
        borderBottomWidth: 1,
    },
    textWrap: {
        width: Style.width,
        height: 150,
        borderColor: '#e5e5e5',
        borderStyle: 'solid',
        borderTopWidth: 1,
        borderBottomWidth: 1,
        marginBottom: 20,

    },
    textInput: {
        padding: 10,
    },

    bottom: {
        width: Style.width,
        height: 1,
        borderColor: '#e5e5e5',
        borderStyle: 'solid',
        borderBottomWidth: 1,
    }
})
export default connect(
    state => ({ userInfo: state.User.userInfo, token: state.User.token }),
    dispatch => ({ unshiftInventroy: bindActionCreators(unshiftInventroy, dispatch) })
)(ChecksAdd)